package me.macd.mindoc.controller;

import me.macd.mindoc.model.BookResult;
import me.macd.mindoc.model.Label;
import me.macd.mindoc.model.Members;
import me.macd.mindoc.service.BookService;
import me.macd.mindoc.service.LabelService;
import me.macd.mindoc.util.Page;
import me.macd.mindoc.util.constants.Constants;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;

import java.util.HashMap;
import java.util.Map;

/**
 * @program: mindoc
 * @description: ${description}
 * @author: 2018-09-21
 * @create: 2018-09-21 22:20
 */
@Controller
public class HomeController {

    @Autowired
    private BookService bookService;

    @Autowired
    private LabelService labelService;

    @RequestMapping(value = "/", method = RequestMethod.GET)
    public String index(@RequestParam(value = "page", required = false, defaultValue = "1") Integer pageIndex, Model model) {
        int memberId = 0;
        Subject subject = SecurityUtils.getSubject();
        if (subject.isAuthenticated()) {
            Members members = (Members) subject.getSession().getAttribute(Constants.SESSION_USER_INFO);
            if (members != null) {
                memberId = members.getMemberId();
            }
        }

        Page<BookResult> page = bookService.findForHomeToPager(pageIndex, 18, memberId);

        if (page.getTotalCount() > 0) {
            // todo
            model.addAttribute("PageHtml", "");
        } else {
            model.addAttribute("PageHtml", "");
        }

        model.addAttribute("TotalPages", Math.ceil(page.getTotalCount() / 18.0));
        model.addAttribute("Lists", page.getItems());

        Page<Label> labelPage = labelService.findToPager(1, 10);

        model.addAttribute("Labels", labelPage.getItems());

        model.addAllAttributes(Common.map("HomeController", "Index"));

        return "home/index";
    }
}
